<template>
    <section class="cus-service">
        <div class="cp-container">
            <el-breadcrumb separator-class="el-icon-arrow-right" class="bread">
                <el-breadcrumb-item :to="{ path: '/community/expert' }">专家中心</el-breadcrumb-item>
                <el-breadcrumb-item>专家详情</el-breadcrumb-item>
            </el-breadcrumb>
            <process-state :statusIndex="statusIndex"></process-state>
            <div class="form-info bgf">
                <el-form ref="form" :model="form" :rules="rules" label-width="130px">
                    <el-row :gutter="70">
                        <el-col :span="12">
                            <el-form-item label="服务">
                                {{serviceName}}
                            </el-form-item>
                            <el-form-item label="问题描述" prop="problem">
                                <el-input
                                    v-model.trim="form.problem"
                                    type="textarea"
                                    :rows="14"
                                    resize="none"
                                    maxlength="800"
                                    show-word-limit
                                    :placeholder="placeholder">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="11" style="padding-right: 60px;">
                            <el-form-item label="金额" prop="payAmount" v-if="serviceType==='ENTITY_DELIVER'">
                                <el-input v-model.trim="form.payAmount" size="large" placeholder="请输入金额">
                                    <span slot="suffix" class="suffix flex">元</span>
                                </el-input>
                                <p style="font-size: 10px;color: #999">请提前与商家沟通确定金额，以便交易成功</p>
                            </el-form-item>
                            <el-form-item label="上传附件" >
                                <p class="ct-input-info">支持格式：各类常规文档及图片格式</p>
                                <oss-upload-file
                                    :original-file-list="problemResourcesJson"
                                    :oss-limit="1"
                                    :oss-file-size="10"
                                    oss-value="problemResourcesJson"
                                    @deleteFileCallback="deleteFileCallback"
                                    @handleChangeFile="handleChangeFile">
                                </oss-upload-file>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <section class="total-price flex flex-between">
                    <div class="tips">提交成功后等待专家接受订单</div>
                    <div class="cp-form-btn flex">
                        <div v-if="serviceType!=='ENTITY_DELIVER'" class="money">
                            <span>支付金额</span>
                            <span class="price">&yen;{{$route.query.price || 0}}</span>
                        </div>
                        <el-button :disabled="isDisabled" type="primary" @click="handleSubmit">立即预约</el-button>
                    </div>
                </section>
            </div>
        </div>
        <el-dialog
            width="480px"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            custom-class="dialog-form"
            center>
            <div class="dialog-body flex flex-column flex-center" style="height: 150px;">
                <p class="flex flex-column">
                    <i class="icon icon-success"></i>
                    <span>提交成功</span>
                </p>
                <p style="margin-top: 20px;">专家接受后您会收到短信提醒</p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="jumpLink">确定</el-button>
            </span>
        </el-dialog>
    </section>
</template>
<script lang="ts">
import {Vue, State, Component} from 'nuxt-property-decorator'
import processState from '~/components/community/expert/processState.vue'
import ossUploadFile from '~/components/modules/ossUploadFile.vue'
import {addTalksInfo} from '~/api/community/expert'
import {ciipWebUrl} from '~/../config/server.url.conf'
import ValidateLoginConfirm from '~/method/confirm'

@Component({
    name: 'trade',
    layout: 'community',
    head () {
        const t = this as any
        return {
            title: `提交需求-${t.$route.query.sn}-CIIP社群中心`,
            meta: [
                {hid: 'description', name: 'description', content: `${t.$route.query.sn}，提交您的需求，等待专家接单，为您提供服务。`},
                {name: 'keywords', content: '经验，服务，建筑业专家'}
            ]
        }
    },
    components: {
        processState,
        ossUploadFile
    }
})
export default class PageCustomerService extends Vue {
    @State userinfo: any
    @State haslogin: any
    validatePrice = (rule: any, value: any, callback: any) => {
        this.validatePriceNumber(rule, value, callback)
    }
    statusIndex: number = 0
    form: any = {
        problemResourcesJson: [],
        problemResourcesJsonNum: '',
        payAmount: '',
        problem: '',
        serviceModeId: '', // 服务形式id
        expertServiceId: '', // 专家服务id
        createUserId: ''
    }
    problemResourcesJson: any = []
    serviceName: any = ''
    serviceType: any = ''
    isDisabled: boolean = false
    dialogVisible: boolean = false
    placeholder: string = ''
    rules: any = {
        problem: [
            {required: true, message: '请输入', trigger: 'blur'}
        ],
        payAmount: [
            {required: true, message: '请输入', trigger: 'blur'},
            {validator: this.validatePrice, trigger: 'blur'}
        ],
        problemResourcesJsonNum: [
            {required: true, message: '请上传', trigger: 'change'}
        ]
    }
    mounted () {
        this.initInfo()
    }
    initInfo () {
        this.serviceName = this.$route.query.sn
        this.serviceType = this.$route.query.st
        this.form.serviceModeId = this.$route.query.sId
        this.form.expertServiceId = this.$route.params.id
        if (this.serviceType === 'ENTITY_DELIVER') {
            this.placeholder = '详细描述您的需求，希望完成的时间节点和预算等，并说明项目的相关情况，有利于专家给出针对性的方案'
        } else {
            this.placeholder = '详细描述您想请教的问题，有利于专家给出针对性的回答'
        }
    }
    handleChangeFile (json: any) {
        this.form[json.filevalue] = [json.data]
        this.form[json.filevalue + 'Num'] = json.num > 0 ? json.num.toString() : ''
        this.validateFieldInput(json.filevalue + 'Num')
    }
    validateFieldInput (key:any) {
        try {
            (this.$refs.form as any).validateField(key)
        } catch (e) {
            console.log('validateFieldInput [ validateField ] with valid prop string!')
        }
    }
    deleteFileCallback (json: any) {
        const del = this.form.delIds ? this.form.delIds.split(',') : []
        del.push(json.id)
        this.form.delIds = del.join(',')
    }
    validateLoginConfirm () {
        const confirm = new ValidateLoginConfirm({that: this})
        confirm.validateLoginConfirmForParams(
            '您尚未登录，登录即可预约！',
            '立即登录',
            ciipWebUrl + '/login?redirectUrl=' + window.location.href
        )
    }
    handleSubmit () {
        if (!this.haslogin) {
            this.validateLoginConfirm()
        } else {
            this.submitForm()
        }
    }
    submitForm () {
        (this.$refs.form as any).validate((valid: any) => {
            if (valid) {
                this.isDisabled = true
                const form:any = {...this.form}
                if (this.serviceType === 'ENTITY_DELIVER') {
                    form.payAmount = form.payAmount ? Number(form.payAmount) : ''
                }
                form.problemResourcesJson = JSON.stringify(form.problemResourcesJson)
                form.createUserId = this.userinfo.id
                delete form.problemResourcesJsonNum
                const submitAjax = async (fn: any) => {
                    const {data} = await fn(form)
                    if (data.code >= 0) {
                        this.dialogVisible = true
                        this.isDisabled = false
                    } else {
                        this.$message.error(data.msg)
                    }
                }
                submitAjax(addTalksInfo)
            } else {
                console.log('error submit!!')
                return false
            }
        })
    }
    jumpLink () {
        this.dialogVisible = false
        window.open(ciipWebUrl + '/me/order/serve', '_self')
    }
    validatePriceNumber (rule: any, value: any, callback: any) {
        if (isNaN(Number(value)) || Number(value) < 0) {
            callback(new Error('请输入大于0的数字'))
        } else {
            const field = rule.field
            const arr = field.split('.')
            const len = arr.length
            if (len === 1) {
                this.form[arr[0]] = Number(value).toFixed(2)
            } else if (len === 3) {
                this.form[arr[0]][arr[1]][arr[2]] = Number(value).toFixed(2)
            }
            callback()
        }
    }

}
</script>
<style lang="scss" scoped>
    .cus-service {
        background: #f7f7f7;
        .el-breadcrumb__inner.is-link:hover{
            color: #11a9e8;
        }
        .bgf {
            background: #fff;
        }

        .bread {
            height: 60px;
            line-height: 60px;
        }
        .form-info{
            padding: 25px;
            margin: 20px 0;
            .el-form-item__label{
                color: #666;
            }
            .ct-input-info{
                color: #ff5a5a;
                font-size: 10px;
            }
            .suffix{
                padding: 5px 10px 0 0;
            }
            .el-button--primary{
                width: 120px;
                height: 36px;
                background: #11a9e8;
                border-color: #11a9e8;
            }
            .question{}
            .total-price{
                margin-top: 42px;
                padding: 14px 25px;
                background: #FCFAF6;
                align-items: center;
                .tips{
                    font-size: 14px;
                    color: #999;
                }
                .cp-form-btn{
                    align-items: center;
                    .money{
                        font-size: 12px;
                        font-style: normal;
                        color: #666;
                        span{
                            &.price{
                                margin-left: 10px;
                                margin-right: 25px;
                                font-size: 20px;
                                color: #ff5a5a;
                            }

                        }
                    }
                }
            }
        }
        .dialog-body{
            font-size: 14px;
            span{
                margin-top: 10px;
                color: #11a9e8;
            }
        }
    }
</style>
<style lang="scss">
    .cus-service {
        .el-breadcrumb__inner.is-link:hover{
            color: #11a9e8;
        }
    }
</style>
